package com.caxxb.controller;

import com.caxxb.common.R;
import com.caxxb.entity.OrderPojo;
import com.caxxb.service.GameService;
import com.caxxb.service.OrderCountService;
import com.caxxb.service.OrderService;
import com.caxxb.service.impl.GameServiceImpl;
import com.caxxb.service.impl.OrderCountServiceImpl;
import com.caxxb.service.impl.OrderServiceImpl;
import com.caxxb.util.PageData;
import com.caxxb.util.QueryResponseData;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("order")
@CrossOrigin("*")
public class OrderController {

    private OrderService orderService=new OrderServiceImpl();

    private OrderCountService service = new OrderCountServiceImpl();

    private GameService gameService = new GameServiceImpl();

    //前台给用户展示订单
    @GetMapping("show")
    public R getOrdersByUserId(@RequestParam(value = "pageNo",defaultValue ="1",required = false )int pageNo, @RequestParam(value = "pageSize",defaultValue ="10",required = false )int pageSize, HttpSession session){
        int userid = (int) session.getAttribute("user");
        PageData<OrderPojo> pageData = orderService.getOrdersByUserId(userid, pageNo, pageSize);
        return R.success(pageData);
    }

    @GetMapping("query")
    public QueryResponseData getByPage(@RequestParam(name = "page", required = false, defaultValue = "1") int pageNo, @RequestParam(name = "limit", required = false, defaultValue = "10") int pageSize, @RequestParam(name = "keywords", required = false, defaultValue = "%%") String keywords){
        PageData pageData = orderService.queryOrderByPage(pageNo,pageSize,keywords);
        QueryResponseData<OrderPojo> queryResponseData = new QueryResponseData<>();
        //数量
        queryResponseData.setCount(pageData.getTotal());
        queryResponseData.setData(pageData.getData());
        return queryResponseData;
    }


    @GetMapping("ordercount")
    public QueryResponseData getOrderCount() {

        List orderCount = service.getOrderCount();

        QueryResponseData responseData = new QueryResponseData();
        if (orderCount.size()==0) {
            responseData.setMsg("fail");
        } else {
            responseData.setData(orderCount);
        }
        return responseData;

    }


    @DeleteMapping("refund/{orderid}")
    public R Refund(@PathVariable int orderid,HttpSession session){
        System.out.println("订单id:"+orderid);
        //根据订单id得到订单信息
        OrderPojo order = orderService.getOrderByOrderId(orderid);
        //得到订单id
        int order_id = order.getOrder_id();

        //得到游戏id
        int game_id = order.getGame_id();

        boolean flag = orderService.delOrderByOrderId(order_id);
        boolean delflag=false;

        if(flag){
            delflag = gameService.delSales(game_id);
        }


        return R.success(order.getOrder_price());
    }

}
